<?php
class send_email {
  var $subject;
  var $message;
  var $from_email;
  var $from_name;
  var $reply_to;
  var $to_email;
  var $to_name;
  var $headers = array();
  var $error = "No error occurred.";

  function send() {
    // I think this was a bad idea.
    // $this->process();
    if (!$this->validate()) return false;

    $headers = "From: {$this->from_name} <{$this->from_email}>\r\n" .
       "Reply-To: {$this->reply_to}\r\n" .
       'X-Mailer: PHP/' . phpversion() . "\r\n";

    foreach ($this->headers as $header) {
      $headers .= "{$header['name']}: {$header['value']}\r\n";
    }
    if (!mail($this->to_email, $this->subject, $this->message, $headers)) {
      $this->error = "Unspecified error while executing mail()";
      return false;
    }
    return true;
  }

  function test() {
    $this->process();
    $this->validate();

    $headers = "From: {$this->from_name} <{$this->from_email}>\r\n" .
       "To: {$this->to_name} <{$this->to_email}>\r\n" .
       "Reply-To: {$this->reply_to}\r\n" .
       'X-Mailer: PHP/' . phpversion();

    foreach ($this->headers as $header) {
      $headers .= "{$header['name']}: {$header['value']}\r\n";
    }
    
    echo $this->to_email . "\n";
    echo $this->subject . "\n";
    echo $this->message . "\n";
    print_r($headers);
  }
  
  function check_email($email) {
    if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
      return true;
    } else {
      return false;
    }
  }

  function validate() {
    if (!$this->check_email($this->from_email)) {
      $this->error = "From email is not valid";
      return false;
    }
    if (!$this->check_email($this->to_email)) {
      $this->error = "To email is not valid";
      return false;
    }
    if (!$this->check_email($this->reply_to)) {
      $this->error = "Reply-to email is not valid";
      return false;
    }
    if (!$this->subject) {
      $this->error = "Subject not set";
      return false;
    }
    if (!$this->message) {
      $this->error = "Message not set";
      return false;
    }
    return true;
  }

  function process() {
    if (!isset($this->from_name)) $this->from_name = $this->from_email;
    if (!isset($this->to_name)) $this->to_name = $this->to_email;
    if (!isset($this->reply_to)) $this->reply_to = $this->from_email;
  }

  function add_header($name, $value) {
    array_push($this->headers,
      array(
        'name' => $name,
        'value' => $value
      )
    );
  }


}
?>